import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class EventChannelPage extends StatefulWidget {
  const EventChannelPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return EventChannelPageState();
  }
}

///代码清单9-7
///lib/EventChannelPage.dart
class EventChannelPageState extends State<EventChannelPage> {
  ///回传的消息标识
  String _reciverStr = "";
  //创建 EventChannel
  static const eventChannel = EventChannel('flutter_and_native_103');
  ///消息流
  StreamSubscription? _streamSubscription;

  @override
  void initState() {
    super.initState();
    ///设置监听
    _streamSubscription =
        eventChannel.receiveBroadcastStream().listen((Object? event) {
      ///成功消息回调
      setState(() {
        _reciverStr = "回传数据: " + event.toString();
      });
    }, onError: (Object event) {
      ///失败消息回调
      setState(() {
        _reciverStr = "回传数据: " + event.toString();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(_reciverStr),
      ),
    );
  }
  @override
  void dispose() {
    super.dispose();
    ///移除监听
    if (_streamSubscription != null) {
      _streamSubscription?.cancel();
      _streamSubscription = null;
    }
  }
}
